package com.chance.cc.crawler.development.scripts.lou;

import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpConstant;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequest;
import com.chance.cc.crawler.core.downloader.HttpRequestBody;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Json;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.LabelTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2021/2/23 12:57
 * @Description
 *      杭州19lou
 **/
public class LouCrawlerScript extends CrawlerCommonScript {

    private Logger log = LoggerFactory.getLogger(LouCrawlerScript.class);
    private static final String REQUEST_AGAIN_TAG = "19lou_request_again";

    private static final String SEARCH_ENTRANCE_URL = "https://www.19lou.com/search/thread/index";
    private static final String SEARCH_URL = "https://www.19lou.com/search/thread\\S*";
    private static final String ITEM_URL_ONE = "http[s]*://www.19lou.com/forum-\\d+-thread-\\d+-1-1.html";
    private static final String ITEM_URL_TWO = "http[s]*://www.19lou.com/board-\\d+-thread-\\d+-1.html";
    private static final String COMMENT_URL = "http[s]*://www.19lou.com/\\S*.html#comment";

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return "19lou";
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(SEARCH_ENTRANCE_URL);
        addUrlRegular(SEARCH_URL);
        addUrlRegular(ITEM_URL_ONE);
        addUrlRegular(ITEM_URL_TWO);
        addUrlRegular(COMMENT_URL);
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }

    @Override
    public List<CrawlerRecord> prepareRequest(CrawlerRequestRecord requestRecord, List<CrawlerRequestRecord> supportSourceRecords) {
        List<CrawlerRecord> crawlerRecords = new ArrayList<>();

        for (CrawlerRequestRecord supportSourceRecord : supportSourceRecords) {
            String url = supportSourceRecord.getHttpRequest().getUrl();
            if (url.contains("keys")) {
                initKeyword(requestRecord, supportSourceRecord, crawlerRecords);
            }
        }

        return crawlerRecords;
    }

    /**
     * 解析链接方法
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();

        if (!httpPage.isDownloadSuccess()) {
            log.error("19lou page download error!will retry");
            requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        String requestUrl = httpPage.getRequest().getUrl();
        if(requestUrl.matches(SEARCH_URL)){
            searchUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }else if(requestUrl.matches(ITEM_URL_ONE) || requestUrl.matches(ITEM_URL_TWO)){
            itemUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }else if(requestUrl.matches(COMMENT_URL)){
            commentUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        return parsedLinks;
    }

    private void searchUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage,List<CrawlerRequestRecord> parsedLinks){
        //翻页
        String nextUrl = httpPage.getHtml().xpath("//a[text()='下一页']/@href").get();
        if(StringUtils.isNotBlank(nextUrl)){
            nextUrl = "https:" + StringEscapeUtils.unescapeHtml(nextUrl);
            CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(nextUrl)
                    .releaseTime(System.currentTimeMillis())
                    .httpHeads(crawlerRequestRecord.getHttpRequest().getHeaders())
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            parsedLinks.add(turnRecord);
        }

        //详情页
        List<Selectable> nodes = httpPage.getHtml().xpath("//ul[@class=\"detailtz clearall\"]/li").nodes();
        for (Selectable node : nodes) {
            String itemUrl = node.xpath(".//p[@class=\"title\"]/a/@href").get();
            if(StringUtils.isBlank(itemUrl)){
                continue;
            }else{
                itemUrl = "https:" + itemUrl.trim();
            }

            CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRequestRecord)
                    .httpUrl(itemUrl)
                    .releaseTime(System.currentTimeMillis())
                    .httpHeads(crawlerRequestRecord.getHttpRequest().getHeaders())
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            parsedLinks.add(itemRecord);
        }
    }

    private void itemUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage,List<CrawlerRequestRecord> parsedLinks){
        String requestUrl = httpPage.getRequest().getUrl();
        //点赞数
        String url = "";
        if(requestUrl.matches(ITEM_URL_TWO)){
            url = "https://www.19lou.com/board/rate/userInfoList";
        }else if(requestUrl.matches(ITEM_URL_ONE)){
            url = "https://www.19lou.com/userInfoList";
        }
        CrawlerRequestRecord likeRecord = CrawlerRequestRecord.builder()
                .itemPageRequest(crawlerRequestRecord)
                .httpUrl(url)
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                .needWashed(false)
                .build();
        HttpRequest httpRequest = likeRecord.getHttpRequest();
        httpRequest.setMethod(HttpConstant.Method.POST);
        httpRequest.addHeader("Cookie",crawlerRequestRecord.getHttpRequest().getHeaders().get("Cookie"));
        httpRequest.addHeader("Referer",httpPage.getRequest().getUrl());
        String pid = httpPage.getHtml().xpath("//div[contains(@class,'first')]/@id").get();
        String tid = httpPage.getHtml().xpath("//input[@name=\"tid\"]/@value").get();
        String fid = httpPage.getHtml().xpath("//input[@name=\"fid\"]/@value").get();
        Map<String,Object> params = new HashMap<>();
        params.put("tid",tid);
        params.put("pid",pid);
        params.put("rate",1);//请求的类型（1：赞；2：踩）
        if(requestUrl.matches(ITEM_URL_ONE)){
            params.put("fid",fid);
        }else if(requestUrl.matches(ITEM_URL_TWO)){
            params.put("bid",fid);
        }
        httpRequest.setRequestBody(HttpRequestBody.form(params,"UTF-8"));
        parsedLinks.add(likeRecord);

        //comment
        CrawlerResultTags resultTags = crawlerRequestRecord.tagsCreator().resultTags();
        if(resultTags.hasDataType(comment)){
            resultTags.getCategoryTag().removeLabelTag("comment");

            CrawlerRequestRecord filterRecord = resultTags.getCategoryTag().getKVTagObjVal("comment_filter_record", CrawlerRequestRecord.class);
            if(filterRecord == null){
                log.error("filter record can not null !");
                return;
            }
            //查找最后一页的评论
            String lastUrl = httpPage.getHtml().xpath("//a[@class=\"page-last\"]/@href").get();
            if(StringUtils.isNotBlank(lastUrl)){
                lastUrl = "https:" + lastUrl + "#comment";
            }else{
                lastUrl = requestUrl + "#comment";
            }
            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(lastUrl)
                    .releaseTime(System.currentTimeMillis())
                    .httpHeads(crawlerRequestRecord.getHttpRequest().getHeaders())
                    .notFilterRecord()
                    .copyBizTags()
                    .needWashed(true)
                    .resultLabelTag(comment)
                    .build();
            commentRecord.setFilter(filterRecord.getFilter());
            commentRecord.setFilterInfos(filterRecord.getFilterInfos());
            parsedLinks.add(commentRecord);
        }
    }

    private void commentUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage,List<CrawlerRequestRecord> parsedLinks){
        //翻页
        String nextUrl = httpPage.getHtml().xpath("//a[@class=\"page-prev\"]/@href").get();
        if(StringUtils.isBlank(nextUrl)){
            return;
        }else{
            nextUrl = "https:" + nextUrl + "#comment";
        }

        CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                .turnPageRequest(crawlerRequestRecord)
                .httpUrl(nextUrl)
                .releaseTime(System.currentTimeMillis())
                .httpHeads(crawlerRequestRecord.getHttpRequest().getHeaders())
                .copyBizTags()
                .needWashed(true)
                .copyResultTags()
                .build();
        parsedLinks.add(commentRecord);
    }
    @Override
    public void afterInternalDownload(CrawlerRequestRecord crawlerRecord, List<CrawlerRequestRecord> internalDownloadRecords, List<CrawlerRequestRecord> links) {
        for (CrawlerRequestRecord internalDownloadRecord : internalDownloadRecords) {
            HttpPage httpPage = internalDownloadRecord.getInternalDownloadPage();
            try{
                String likes = httpPage.getJson().jsonPath($_type + ".data.rateCount").get();
                likes = StringUtils.isNotBlank(likes) ? likes : "0";
                crawlerRecord.getHttpRequest().addExtra("likes",likes);
            }catch (Exception e){
                log.error(e.getMessage());
                requestAgainCrawlerRecord(links,crawlerRecord);
                crawlerRecord.setNeedWashPage(false);
                return;
            }
        }
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();

        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(interaction)) {
            crawlerDataList.add(washNewsInteraction(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(comment)) {
            crawlerDataList.addAll(washComment(crawlerRecord, page));
        }

        return crawlerDataList;
    }

    private CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String[] split = itemUrl.split("-");
        String articleKey = split[3];

        String title = httpPage.getHtml().xpath("//h1//span/text()").get();
        String author = httpPage.getHtml().xpath("//div[@class=\"user-name\"]//a/span/text()|//div[@class=\"J_post post first shadow\"]//a[@class=\"name\"]/span/text()|//div[@class=\"clearall floor first\"]//a[@class=\"fb\"]/span/text()").get();
        String releaseTime = httpPage.getHtml().xpath("//span[@class=\"u-add-ft\"]/@title|//span[@class=\"fl\"]/@title|//li[contains(@title,'发表于')]/@title").get();
        List<String> all = httpPage.getHtml().xpath("//div[@class=\"J_post post first newPost shadow\"]//div[@class=\"post-cont\"]//text()|//div[@class=\"J_post post first shadow\"]//div[@class=\"post-cont\"]//text()|//div[@class=\"clearall floor first\"]//div[@class=\"thread-cont\"]//text()").all();
        StringBuffer conents = new StringBuffer();
        for (String articleText : all) {
            if(StringUtils.isBlank(articleText) || (StringUtils.isNotBlank(articleText) && "收藏".equals(articleText))){
                continue;
            }
            conents.append(articleText).append(" ");
        }

        CrawlerData crawlerData = null;
        try {
            Long releaseTimeToLong =  DateUtils.parseDate(releaseTime.trim(), "发表于yyyy-MM-dd HH:mm:ss","发表于yyyy-MM-dd HH:mm").getTime() ;
            crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                    .url(itemUrl)
                    .releaseTime(releaseTimeToLong)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                    .addContentKV(Field_Content, conents.toString())
                    .addContentKV(Field_Title, title)
                    .addContentKV(Field_Author, author)
                    .build();
        } catch (ParseException e) {
            log.error(e.getMessage());
        }
        return crawlerData;
    }

    private CrawlerData washNewsInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String[] split = itemUrl.split("-");
        String articleKey = split[3];

        String views = httpPage.getHtml().xpath("//div[text()='阅读']/preceding-sibling::em/text()|//em[@id=\"J_threadViewNum\"]/text()|//i[@id=\"J_threadViewNum\"]/text()").get();
        views = StringUtils.isNotBlank(views) ? views : "0";
        String comments = httpPage.getHtml().xpath("//span[text()='回帖']/following-sibling::i/text()").get();
        comments = StringUtils.isNotBlank(comments) ? comments : "0";
        String collections = httpPage.getHtml().xpath("//span[text()='收藏' or text()='已收藏']/following-sibling::i/text()").get();
        collections = StringUtils.isNotBlank(collections) ? collections : "0";
        String releaseTime = httpPage.getHtml().xpath("//span[@class=\"u-add-ft\"]/@title|//span[@class=\"fl\"]/@title|//li[contains(@title,'发表于')]/@title").get();
        try {
            Long releaseTimeToLong =  DateUtils.parseDate(releaseTime.trim(), "发表于yyyy-MM-dd HH:mm:ss","发表于yyyy-MM-dd HH:mm").getTime() ;
            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), interaction.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                    .releaseTime(releaseTimeToLong)
                    .url(itemUrl)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                    .addContentKV(Field_I_Comments, comments)
                    .addContentKV(Field_I_Views,views)
                    .addContentKV(Field_I_Collection,collections)
                    .addContentKV(Field_I_Likes,(String) crawlerRequestRecord.getHttpRequest().getExtras().get("likes"))
                    .build();

            return crawlerData;
        } catch (ParseException e) {
            log.error(e.getMessage());
        }

        return null;

    }

    public List<CrawlerData> washComment(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        String requestUrl = httpPage.getRequest().getUrl();
        String[] split = requestUrl.split("-");
        String articleKey = split[3];

        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@itemprop=\"replyPost\"]").nodes();
        for (int i = nodes.size()-1; i >= 0 ; i--) {
            Selectable node= nodes.get(i);
            String author = node.xpath(".//a[@class=\"name\"]/span/text()").get();
            StringBuffer content = new StringBuffer();
            List<String> all = node.xpath(".//div[@class=\"post-cont\"]//text()").all();
            for (String data : all) {
                if(StringUtils.isBlank(data)){
                    continue;
                }
                content.append(data).append(" ");
            }
            String releaseTime = node.xpath(".//span[@class=\"fl\"]/text()").get();

            String commentId = node.xpath("./@id").get();
            CrawlerData crawlerData = null;
            try {
                crawlerData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), comment.enumVal(), commentId))
                        .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                        .releaseTime(DateUtils.parseDate(releaseTime.trim(),"发表于: yyyy-MM-dd HH:mm","发表于yyyy-MM-dd HH:mm:ss").getTime())
                        .url(requestUrl)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                        .addContentKV(Field_Author, author)
                        .addContentKV(Field_Content, content.toString())
                        .build();
                crawlerDataList.add(crawlerData);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return crawlerDataList;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private void requestAgainCrawlerRecord(List<CrawlerRequestRecord> crawlerRequestRecords, CrawlerRequestRecord crawlerRecord) {
        CrawlerBusinessTags crawlerBusinessTags = crawlerRecord.tagsCreator().bizTags();
        int count = 0;
        if (crawlerBusinessTags.hasKVTag(REQUEST_AGAIN_TAG)) {
            count = (int) crawlerBusinessTags.getCategoryTag().getKVTag(REQUEST_AGAIN_TAG).getVal();
            if (count >= 5) {
                log.error("19lou download page the number of retries exceeds the limit" +
                        ",request url {}", crawlerRecord.getHttpRequest().getUrl());
                return;
            }
        }

        String requestUrl = crawlerRecord.getHttpRequest().getUrl();
        LabelTag type = crawlerRecord.tagsCreator().requestTags().getCategoryTag().getLabelTags().get("turn_page_item_request");
        CrawlerRequestRecord crawlerRequestRecord = null;
        if(type == null){
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }else{
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }

        if (crawlerRequestRecord == null) {
            return;
        }

        crawlerRequestRecord.getHttpRequest().setExtras(crawlerRecord.getHttpRequest().getExtras());
        crawlerRequestRecord.getHttpRequest().setHeaders(crawlerRecord.getHttpRequest().getHeaders());
        crawlerRequestRecord.setNeedWashPage(crawlerRecord.isNeedWashPage());
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV(REQUEST_AGAIN_TAG, ++count);
        crawlerRequestRecord.setInternalDownloadPage(crawlerRecord.getInternalDownloadPage());
        crawlerRequestRecords.add(crawlerRequestRecord);
    }

    private void initKeyword(CrawlerRequestRecord requestRecord, CrawlerRequestRecord supportSourceRecord, List<CrawlerRecord> crawlerRecords) {
        HttpPage internalDownloadPage = supportSourceRecord.getInternalDownloadPage();
        String sourceUrl = (String ) requestRecord.getHttpRequest().getExtras().get("searchKwSourceUrl");
        if(StringUtils.isEmpty(sourceUrl)){
            log.error("sourceUrl can not null !");
            return;
        }
        Json json = internalDownloadPage.getJson();
        String msg = json.jsonPath($_type + ".msg").get();
        if (!"success".equals(msg)) {
            log.error("keyword page [{}] download error!", internalDownloadPage.getRequest().getUrl());
            return;
        }

        List<String> all = json.jsonPath($_type + ".content").all();
        for (String data : all) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String keyword = jsonObject.getString("keyword");

            String itemUrl = null;
            try {
                itemUrl = String.format(sourceUrl, URLEncoder.encode(keyword, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(requestRecord)
                    .httpUrl(itemUrl)
                    .releaseTime(System.currentTimeMillis())
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            HttpRequest httpRequest = turnRecord.getHttpRequest();
            httpRequest.addHeader("Cookie",(String) requestRecord.getHttpRequest().getExtras().get("Cookie"));
            httpRequest.addHeader("Referer",requestRecord.getHttpRequest().getUrl());
            crawlerRecords.add(turnRecord);
        }
    }

    private static String getString(String regx, String input) {
        Pattern compile = Pattern.compile(regx);
        Matcher matcher = compile.matcher(input);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }
}
